<template>
  <el-drawer :title="$t('message.bjhyxx')" :visible.sync="isShow" size="50%">
    <div>
      <el-form
        ref="form"
        class="doumee-form"
        :rules="rulers"
        :model="param"
        label-width="auto"
        label-suffix="："
        @submit.native.prevent
      >
        <el-form-item :label="$t('message.sjh')" prop="phone">
          <el-input
            v-model="param.phone"
            type="text"
            :placeholder="$t('message.qsr') + $t('message.sjh')"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item :label="$t('message.nc')" prop="nickName">
          <el-input
            v-model="param.nickName"
            type="text"
            :placeholder="$t('message.qsr') + $t('message.nc')"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item v-if="fyms === '0'" :label="$t('message.zsxm')" prop="realName">
          <el-input v-model="param.realName" :placeholder="$t('message.qsr') + $t('message.zsxm')" />
        </el-form-item>
        <el-form-item v-if="fyms !== '0'" :label="$t('message.zsxm')">
          <el-input v-model="param.realName" :placeholder="$t('message.qsr') + $t('message.zsxm')" />
        </el-form-item>
        <el-form-item :label="$t('message.csrq')">
          <el-date-picker
            v-model="param.birthday"
            class="w400"
            value-format="yyyy-MM-dd"
            type="date"
            :placeholder="$t('message.qxz') + $t('message.csrq')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sex')">
          <el-radio v-model="param.sex" label="0">{{ $t('message.bm') }}</el-radio>
          <el-radio v-model="param.sex" label="1">{{ $t('message.nan') }}</el-radio>
          <el-radio v-model="param.sex" label="2">{{ $t('message.nv') }}</el-radio>
        </el-form-item>
        <el-form-item
          v-if="fyms === '0'"
          :label="$t('message.sfzh')"
          prop="identityNumber"
        >
          <el-input
            v-model="param.identityNumber"
            type="text"
            onkeyup="value=value.replace(/[^\X0-9]/g, '')"
            oninput="if(value.length>18)value=value.slice(0,18)"
            :placeholder="$t('message.qsr') + $t('message.sfzhm')"
          />
        </el-form-item>
        <el-form-item v-if="fyms !== '0'" :label="$t('message.sfzh')">
          <el-input
            v-model="param.identityNumber"
            type="text"
            onkeyup="value=value.replace(/[^\X0-9]/g, '')"
            oninput="if(value.length>18)value=value.slice(0,18)"
            :placeholder="$t('message.qsr') + $t('message.sfzhm')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.rlcj')" prop="showFaceUrl">
          <div class="df_ac">
            <div class="img_warp">
              <img
                :src="param.showFaceUrl ? param.showFaceUrl : faceimg"
                class="mr20"
                style="width: 80px; height: 80px"
                alt=""
              >
              <div v-show="param.showFaceUrl" class="delete pointer">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage"
                />
              </div>
            </div>
            <el-button type="primary" @click="acquisitionFace">
              <div class="df_ac">
                <img
                  src="@/assets/icon/ic_caiji.png"
                  style="width: 13px; margin-right: 6px"
                  alt=""
                >
                <span>{{ $t('message.caji') }}</span>
              </div>
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-camera"
              class="mr10"
              @click="openCamera"
            >{{ $t('message.pashi') }}</el-button>
            <el-upload
              class="device-uploader"
              accept=".jpg,.png"
              :auto-upload="false"
              :action="uploadFileUrl"
              :data="uploadParam"
              :show-file-list="false"
              :on-change="addFileChange"
            >
              <el-button type="primary" icon="el-icon-upload2">{{ $t('message.upload') }}</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            :loading="editLoding"
            type="primary"
            @click="onSubmit()"
          >{{ $t('message.tj') }}</el-button>
          <el-button @click="isShow = false">{{ $t('message.qx') }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <transition name="fade">
      <Cropper
        v-if="dialogCropperVisible"
        :option-img="optionImg"
        :fileinfo="fileinfo"
        use-type="MEMBER_IMG"
        :fixed-number="[500, 500]"
        @formSubmit="cropperSubmit"
        @formClose="cropperClose"
      />
    </transition>
    <el-dialog
      :title="$t('message.pashi')"
      :visible.sync="paisheModal"
      width="760px"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      append-to-body
      @close="closeCamera"
    >
      <video
        v-show="isShowCamera"
        id="videoCamera"
        :width="videoWidth"
        :height="videoHeight"
      />
      <canvas
        v-show="!isShowCamera"
        id="canvasCamera"
        style="display: none"
        :width="videoWidth"
        :height="videoHeight"
      />
      <span slot="footer">
        <div>
          <el-button @click="closeCamera">{{ $t('message.qx') }}</el-button>
          <el-button
            v-show="blobFileCamera"
            type="primary"
            @click="resetCamera"
          >{{ $t('message.chonpa') }}</el-button>
          <el-button
            v-show="blobFileCamera"
            :loading="cameraLoading"
            type="primary"
            @click="enterCamera"
          >{{ $t('message.ksjc') }}</el-button>
          <el-button
            v-show="!blobFileCamera"
            type="primary"
            @click="setImage"
          >{{ $t('message.pashi') }}</el-button>
        </div>
      </span>
    </el-dialog>

    <CropperCopy
      v-if="isShowCropper"
      :option-img="blobFileCamera"
      use-type="MEMBER_IMG"
      :fixed-number="[500, 500]"
      @formSubmit="cropperSubmit"
      @formClose="cropperCameraClose"
    />
  </el-drawer>
</template>

<script>
import { uploadFile, changeMemberInfoPc, memberDetailInfo, configList, collectFace } from '@/api'
import Cropper from '@/components/cropper'
import CropperCopy from './cropper.vue'
export default {
  components: {
    Cropper,
    CropperCopy
  },
  data() {
    return {
      isShowCamera: true,
      cameraLoading: false,
      videoWidth: 700,
      videoHeight: 525,
      mediaStreamCamera: '',
      blobFileCamera: '',
      isShowCropper: false,
      // 以上是拍摄
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'MEMBER_IMG'
      },
      dialogCropperVisible: false,
      optionImg: '',
      files: {},
      fileinfo: {},
      modalDialog: this.$store.getters.dialog,
      isShowMember: false,
      caijiModal: false,
      paisheModal: false,
      xdLoding: false,
      isShow: false,
      loding: false,
      editLoding: false,
      firstQueryTime: '',
      param: {},
      fyms: '0',
      codeBtnText: this.$t('message.hqyzm'),
      time: 60,
      codeDsiabled: false,
      linkPhone: '',
      rulers: {
        nickName: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.nc'), trigger: 'blur' },
          { min: 1, max: 8, message: this.$t('message.cdydb'), trigger: 'blur' }
        ],
        identityNumber: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.sfzh'), trigger: 'blur' }
          // ,
          // {
          //   required: true,
          //   pattern:
          //     /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
          //   message: this.$t('message.qsrzqdsfzh'),
          //   trigger: 'blur'
          // }
        ],
        realName: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.zsxm'), trigger: 'blur' }
        ],
        phone: [
          { required: true, message: this.$t('message.sjhmbnwk'), trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: this.$t('message.qsrzqdsjhm'),
            trigger: 'blur'
          }
        ]
      },
      faceimg: require('@/icons/png/default_faceid.png')
    }
  },
  methods: {
    getDetail(id) {
      configList({
        param: {
          type: '7', code: 'EPIDEMIC_PREVENTION_MODE'
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.fyms = res.recordList.find(item => item.code === 'EPIDEMIC_PREVENTION_MODE')
        })
        .catch((err) => {
          console.log(err)
        })
      memberDetailInfo({
        param: {
          memberId: id
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.param = res.record
          this.linkPhone = this.param.phone
        })
        .catch((err) => {
          console.log(err)
        })
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.editLoding = true
          const { param } = this
          changeMemberInfoPc({
            param
          }).then(res => {
            this.editLoding = false
            if (res.errorCode === '000000') {
              this.$message.success(this.$t('message.bccg'))
              // this.$router.go(-1)
              this.isShow = false
              this.$emit('submit')
            }
          }).catch(err => {
            this.editLoding = false
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    acquisitionFace() {
      collectFace({
        param: {
          venueId: sessionStorage.getItem('venueId'),
          shopId: localStorage.getItem('shopId')
        }
      }).then((res) => {
        if (res.errorCode === '000000') {
          this.$set(this.param, 'faceUrl', res.record.insertUrl)
          this.$set(this.param, 'showFaceUrl', res.record.showUrl)
        }
      })
    },
    // 打开相机
    openCamera() {
      this.paisheModal = true
      this.isShowCamera = true
      const that = this
      this.$nextTick(() => {
        var mediaOpts = { audio: false, video: true }
        navigator.mediaDevices.getUserMedia(mediaOpts).then(function(stream) {
          that.mediaStreamCamera = stream
          const video = document.querySelector('#videoCamera')
          if ('srcObject' in video) {
            video.srcObject = stream
          } else {
            video.src = window.URL && window.URL.createObjectURL(stream) || stream
          }
          video.play()
        }).catch(function(err) {
          console.log(err)
        })
      })
    },
    // 重拍
    resetCamera() {
      this.isShowCamera = true
      this.blobFileCamera = ''
      this.openCamera()
    },
    cropperCameraClose() {
      this.isShowCropper = false
      this.blobFileCamera = ''
    },
    // 关闭相机
    closeCamera() {
      this.mediaStreamCamera.getVideoTracks().forEach(function(track) {
        track.stop()
      })
      this.paisheModal = false
    },
    // 点击拍摄
    setImage() {
      const that = this
      that.isShowCamera = false
      const video = document.querySelector('#videoCamera')
      const canvas = document.querySelector('#canvasCamera')
      canvas.getContext('2d').drawImage(video, 0, 0, that.videoWidth, that.videoHeight)
      this.mediaStreamCamera.getVideoTracks().forEach(function(track) {
        track.stop()
      })
      const dataurl = canvas.toDataURL('image/jpg')
      // this.blobFileCamera = that.base64ToFile(dataurl, 'camera')
      this.blobFileCamera = dataurl
    },
    // 确认拍摄
    enterCamera() {
      this.isShowCropper = true
      this.paisheModal = false
      this.isShowCamera = true
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      this.isShowCropper = false
      this.blobFileCamera = ''
      if (config.success) {
        this.$set(this.param, 'faceUrl', config.insertUrl)
        this.$set(this.param, 'showFaceUrl', config.showUrl)
        this.fileinfo = config
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || this.$t('message.scsb'))
        this.dialogCropperVisible = false
      }
    },
    // async addFileChange(file, fileList) {
    //   // 上传，拿到file文件
    //   this.files = file.raw
    //   this.$nextTick(() => {
    //     this.optionImg = URL.createObjectURL(file.raw)
    //     this.fileinfo = file.raw
    //     this.dialogCropperVisible = true
    //   })
    // },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    deleteDeviceConfigAddImage(file, fileList) {
      this.param.faceUrl = ''
      this.param.showFaceUrl = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.img_warp {
  display: flex;
  justify-items: center;
  align-items: center;
  position: relative;
  width: 80px;
  height: 80px;
  margin-right: 20px;
  .delete {
    background-color: rgba(0, 0, 0, 0.5);
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: none;
    align-items: center;
    justify-content: center;
    .icon {
      color: #fff;
    }
  }
  &:hover {
    .delete {
      display: flex;
    }
  }
}
</style>
